package com.hlg.xboot.config;

import com.hlg.xboot.constants.AppConstants;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.session.SessionRepository;
import org.springframework.session.data.redis.RedisOperationsSessionRepository;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.http.HeaderHttpSessionStrategy;
import org.springframework.session.web.http.HttpSessionStrategy;

/**
 * 分布式session配置
 */
@Configurable
@EnableRedisHttpSession
public class HttpSessionConfig {

    @Bean
    public HttpSessionStrategy httpSessionStrategy() {
        HeaderHttpSessionStrategy headerHttpSessionStrategy = new HeaderHttpSessionStrategy();
        headerHttpSessionStrategy.setHeaderName(AppConstants.API_TOKEN);
        return headerHttpSessionStrategy;
    }

    /**
     * 覆盖Session默认的Redis存储配置
     * @param redisTemplate
     * @return
     */
    @Bean
    public SessionRepository sessionRepository(RedisTemplate redisTemplate) {
        RedisOperationsSessionRepository sessionRepository = new RedisOperationsSessionRepository(redisTemplate);
        sessionRepository.setDefaultSerializer(redisTemplate.getDefaultSerializer());
        sessionRepository.setDefaultMaxInactiveInterval(AppConstants.API_TOKEN_TIMEOUT);
        return sessionRepository;
    }

}